home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / pdb.pyc (.txt) < prev    next >
Python Compiled Bytecode  |  2009-11-11  |  43KB  |  1,322 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. '''A Python debugger.'''
  5. import sys
  6. import linecache
  7. import cmd
  8. import bdb
  9. from repr import Repr
  10. import os
  11. import re
  12. import pprint
  13. import traceback
  14.  
  15. class Restart(Exception):
  16.     '''Causes a debugger to be restarted for the debugged python program.'''
  17.     pass
  18.  
  19. _repr = Repr()
  20. _repr.maxstring = 200
  21. _saferepr = _repr.repr
  22. __all__ = [
  23.     'run',
  24.     'pm',
  25.     'Pdb',
  26.     'runeval',
  27.     'runctx',
  28.     'runcall',
  29.     'set_trace',
  30.     'post_mortem',
  31.     'help']
  32.  
  33. def find_function(funcname, filename):
  34.     cre = re.compile('def\\s+%s\\s*[(]' % re.escape(funcname))
  35.     
  36.     try:
  37.         fp = open(filename)
  38.     except IOError:
  39.         return None
  40.  
  41.     lineno = 1
  42.     answer = None
  43.     while None:
  44.         line = fp.readline()
  45.         if line == '':
  46.             break
  47.         
  48.         if cre.match(line):
  49.             answer = (funcname, filename, lineno)
  50.             break
  51.         
  52.         lineno = lineno + 1
  53.         continue
  54.         return answer
  55.  
  56. line_prefix = '\n-> '
  57.  
  58. class Pdb(bdb.Bdb, cmd.Cmd):
  59.     
  60.     def __init__(self, completekey = 'tab', stdin = None, stdout = None):
  61.         bdb.Bdb.__init__(self)
  62.         cmd.Cmd.__init__(self, completekey, stdin, stdout)
  63.         if stdout:
  64.             self.use_rawinput = 0
  65.         
  66.         self.prompt = '(Pdb) '
  67.         self.aliases = { }
  68.         self.mainpyfile = ''
  69.         self._wait_for_mainpyfile = 0
  70.         
  71.         try:
  72.             import readline
  73.         except ImportError:
  74.             pass
  75.  
  76.         self.rcLines = []
  77.         if 'HOME' in os.environ:
  78.             envHome = os.environ['HOME']
  79.             
  80.             try:
  81.                 rcFile = open(os.path.join(envHome, '.pdbrc'))
  82.             except IOError:
  83.                 pass
  84.  
  85.             for line in rcFile.readlines():
  86.                 self.rcLines.append(line)
  87.             
  88.             rcFile.close()
  89.         
  90.         
  91.         try:
  92.             rcFile = open('.pdbrc')
  93.         except IOError:
  94.             pass
  95.  
  96.         for line in rcFile.readlines():
  97.             self.rcLines.append(line)
  98.         
  99.         rcFile.close()
  100.         self.commands = { }
  101.         self.commands_doprompt = { }
  102.         self.commands_silent = { }
  103.         self.commands_defining = False
  104.         self.commands_bnum = None
  105.  
  106.     
  107.     def reset(self):
  108.         bdb.Bdb.reset(self)
  109.         self.forget()
  110.  
  111.     
  112.     def forget(self):
  113.         self.lineno = None
  114.         self.stack = []
  115.         self.curindex = 0
  116.         self.curframe = None
  117.  
  118.     
  119.     def setup(self, f, t):
  120.         self.forget()
  121.         (self.stack, self.curindex) = self.get_stack(f, t)
  122.         self.curframe = self.stack[self.curindex][0]
  123.         self.execRcLines()
  124.  
  125.     
  126.     def execRcLines(self):
  127.         if self.rcLines:
  128.             rcLines = self.rcLines
  129.             self.rcLines = []
  130.             for line in rcLines:
  131.                 line = line[:-1]
  132.                 if len(line) > 0 and line[0] != '#':
  133.                     self.onecmd(line)
  134.                     continue
  135.             
  136.         
  137.  
  138.     
  139.     def user_call(self, frame, argument_list):
  140.         '''This method is called when there is the remote possibility
  141.         that we ever need to stop in this function.'''
  142.         if self._wait_for_mainpyfile:
  143.             return None
  144.  
  145.     
  146.     def user_line(self, frame):
  147.         '''This function is called when we stop or break at this line.'''
  148.         if self._wait_for_mainpyfile:
  149.             if self.mainpyfile != self.canonic(frame.f_code.co_filename) or frame.f_lineno <= 0:
  150.                 return None
  151.             self._wait_for_mainpyfile = 0
  152.         
  153.         if self.bp_commands(frame):
  154.             self.interaction(frame, None)
  155.         
  156.  
  157.     
  158.     def bp_commands(self, frame):
  159.         ''' Call every command that was set for the current active breakpoint (if there is one)
  160.         Returns True if the normal interaction function must be called, False otherwise '''
  161.         if getattr(self, 'currentbp', False) and self.currentbp in self.commands:
  162.             currentbp = self.currentbp
  163.             self.currentbp = 0
  164.             lastcmd_back = self.lastcmd
  165.             self.setup(frame, None)
  166.             for line in self.commands[currentbp]:
  167.                 self.onecmd(line)
  168.             
  169.             self.lastcmd = lastcmd_back
  170.             if not self.commands_silent[currentbp]:
  171.                 self.print_stack_entry(self.stack[self.curindex])
  172.             
  173.             if self.commands_doprompt[currentbp]:
  174.                 self.cmdloop()
  175.             
  176.             self.forget()
  177.             return None
  178.         return 1
  179.  
  180.     
  181.     def user_return(self, frame, return_value):
  182.         '''This function is called when a return trap is set here.'''
  183.         frame.f_locals['__return__'] = return_value
  184.         print >>self.stdout, '--Return--'
  185.         self.interaction(frame, None)
  186.  
  187.     
  188.     def user_exception(self, frame, exc_info):
  189.         (exc_type, exc_value, exc_traceback) = exc_info
  190.         frame.f_locals['__exception__'] = (exc_type, exc_value)
  191.         if type(exc_type) == type(''):
  192.             exc_type_name = exc_type
  193.         else:
  194.             exc_type_name = exc_type.__name__
  195.         print >>self.stdout, exc_type_name + ':', _saferepr(exc_value)
  196.         self.interaction(frame, exc_traceback)
  197.  
  198.     
  199.     def interaction(self, frame, traceback):
  200.         self.setup(frame, traceback)
  201.         self.print_stack_entry(self.stack[self.curindex])
  202.         self.cmdloop()
  203.         self.forget()
  204.  
  205.     
  206.     def displayhook(self, obj):
  207.         '''Custom displayhook for the exec in default(), which prevents
  208.         assignment of the _ variable in the builtins.
  209.         '''
  210.         print repr(obj)
  211.  
  212.     
  213.     def default(self, line):
  214.         if line[:1] == '!':
  215.             line = line[1:]
  216.         
  217.         locals = self.curframe.f_locals
  218.         globals = self.curframe.f_globals
  219.         
  220.         try:
  221.             code = compile(line + '\n', '<stdin>', 'single')
  222.             save_stdout = sys.stdout
  223.             save_stdin = sys.stdin
  224.             save_displayhook = sys.displayhook
  225.             
  226.             try:
  227.                 sys.stdin = self.stdin
  228.                 sys.stdout = self.stdout
  229.                 sys.displayhook = self.displayhook
  230.                 exec code in globals, locals
  231.             finally:
  232.                 sys.stdout = save_stdout
  233.                 sys.stdin = save_stdin
  234.                 sys.displayhook = save_displayhook
  235.  
  236.         except:
  237.             (t, v) = sys.exc_info()[:2]
  238.             if type(t) == type(''):
  239.                 exc_type_name = t
  240.             else:
  241.                 exc_type_name = t.__name__
  242.             print >>self.stdout, '***', exc_type_name + ':', v
  243.  
  244.  
  245.     
  246.     def precmd(self, line):
  247.         """Handle alias expansion and ';;' separator."""
  248.         if not line.strip():
  249.             return line
  250.         args = line.split()
  251.         while args[0] in self.aliases:
  252.             line = self.aliases[args[0]]
  253.             ii = 1
  254.             for tmpArg in args[1:]:
  255.                 line = line.replace('%' + str(ii), tmpArg)
  256.                 ii = ii + 1
  257.             
  258.             line = line.replace('%*', ' '.join(args[1:]))
  259.             args = line.split()
  260.             continue
  261.             line.strip()
  262.         if args[0] != 'alias':
  263.             marker = line.find(';;')
  264.             if marker >= 0:
  265.                 next = line[marker + 2:].lstrip()
  266.                 self.cmdqueue.append(next)
  267.                 line = line[:marker].rstrip()
  268.             
  269.         
  270.         return line
  271.  
  272.     
  273.     def onecmd(self, line):
  274.         '''Interpret the argument as though it had been typed in response
  275.         to the prompt.
  276.  
  277.         Checks whether this line is typed at the normal prompt or in
  278.         a breakpoint command list definition.
  279.         '''
  280.         if not self.commands_defining:
  281.             return cmd.Cmd.onecmd(self, line)
  282.         return self.handle_command_def(line)
  283.  
  284.     
  285.     def handle_command_def(self, line):
  286.         ''' Handles one command line during command list definition. '''
  287.         (cmd, arg, line) = self.parseline(line)
  288.         if cmd == 'silent':
  289.             self.commands_silent[self.commands_bnum] = True
  290.             return None
  291.         if cmd == 'end':
  292.             self.cmdqueue = []
  293.             return 1
  294.         cmdlist = self.commands[self.commands_bnum]
  295.         
  296.         try:
  297.             func = getattr(self, 'do_' + cmd)
  298.         except AttributeError:
  299.             None if arg else cmd == 'silent'
  300.             None if arg else cmd == 'silent'
  301.             func = self.default
  302.         except:
  303.             None if arg else cmd == 'silent'
  304.  
  305.         if func.func_name in self.commands_resuming:
  306.             self.commands_doprompt[self.commands_bnum] = False
  307.             self.cmdqueue = []
  308.             return 1
  309.  
  310.     do_h = cmd.Cmd.do_help
  311.     
  312.     def do_commands(self, arg):
  313.         '''Defines a list of commands associated to a breakpoint
  314.         Those commands will be executed whenever the breakpoint causes the program to stop execution.'''
  315.         if not arg:
  316.             bnum = len(bdb.Breakpoint.bpbynumber) - 1
  317.         else:
  318.             
  319.             try:
  320.                 bnum = int(arg)
  321.             except:
  322.                 print >>self.stdout, 'Usage : commands [bnum]\n        ...\n        end'
  323.                 return None
  324.  
  325.         self.commands_bnum = bnum
  326.         self.commands[bnum] = []
  327.         self.commands_doprompt[bnum] = True
  328.         self.commands_silent[bnum] = False
  329.         prompt_back = self.prompt
  330.         self.prompt = '(com) '
  331.         self.commands_defining = True
  332.         self.cmdloop()
  333.         self.commands_defining = False
  334.         self.prompt = prompt_back
  335.  
  336.     
  337.     def do_break(self, arg, temporary = 0):
  338.         if not arg:
  339.             if self.breaks:
  340.                 print >>self.stdout, 'Num Type         Disp Enb   Where'
  341.                 for bp in bdb.Breakpoint.bpbynumber:
  342.                     if bp:
  343.                         bp.bpprint(self.stdout)
  344.                         continue
  345.                 
  346.             
  347.             return None
  348.         filename = None
  349.         lineno = None
  350.         cond = None
  351.         comma = arg.find(',')
  352.         if comma > 0:
  353.             cond = arg[comma + 1:].lstrip()
  354.             arg = arg[:comma].rstrip()
  355.         
  356.         colon = arg.rfind(':')
  357.         funcname = None
  358.         if colon >= 0:
  359.             filename = arg[:colon].rstrip()
  360.             f = self.lookupmodule(filename)
  361.             if not f:
  362.                 print >>self.stdout, '*** ', repr(filename),
  363.                 print >>self.stdout, 'not found from sys.path'
  364.                 return None
  365.             filename = f
  366.             arg = arg[colon + 1:].lstrip()
  367.             
  368.             try:
  369.                 lineno = int(arg)
  370.             except ValueError:
  371.                 f
  372.                 msg = f
  373.                 print >>self.stdout, '*** Bad lineno:', arg
  374.                 return None
  375.             
  376.  
  377.         f<EXCEPTION MATCH>ValueError
  378.         
  379.         try:
  380.             lineno = int(arg)
  381.         except ValueError:
  382.             f
  383.             f
  384.             f
  385.             
  386.             try:
  387.                 func = eval(arg, self.curframe.f_globals, self.curframe.f_locals)
  388.             except:
  389.                 func = arg
  390.  
  391.             
  392.             try:
  393.                 if hasattr(func, 'im_func'):
  394.                     func = func.im_func
  395.                 
  396.                 code = func.func_code
  397.                 funcname = code.co_name
  398.                 lineno = code.co_firstlineno
  399.                 filename = code.co_filename
  400.             (ok, filename, ln) = self.lineinfo(arg)
  401.             if not ok:
  402.                 print >>self.stdout, '*** The specified object',
  403.                 print >>self.stdout, repr(arg),
  404.                 print >>self.stdout, 'is not a function'
  405.                 print >>self.stdout, 'or was not found along sys.path.'
  406.                 return None
  407.             funcname = ok
  408.             lineno = int(ln)
  409.  
  410.         except:
  411.             ok
  412.  
  413.         if not filename:
  414.             filename = self.defaultFile()
  415.         
  416.         line = self.checkline(filename, lineno)
  417.         if line:
  418.             err = self.set_break(filename, line, temporary, cond, funcname)
  419.             if err:
  420.                 print >>self.stdout, '***', err
  421.             else:
  422.                 bp = self.get_breaks(filename, line)[-1]
  423.                 print >>self.stdout, 'Breakpoint %d at %s:%d' % (bp.number, bp.file, bp.line)
  424.         
  425.  
  426.     
  427.     def defaultFile(self):
  428.         '''Produce a reasonable default.'''
  429.         filename = self.curframe.f_code.co_filename
  430.         if filename == '<string>' and self.mainpyfile:
  431.             filename = self.mainpyfile
  432.         
  433.         return filename
  434.  
  435.     do_b = do_break
  436.     
  437.     def do_tbreak(self, arg):
  438.         self.do_break(arg, 1)
  439.  
  440.     
  441.     def lineinfo(self, identifier):
  442.         failed = (None, None, None)
  443.         idstring = identifier.split("'")
  444.         if len(idstring) == 1:
  445.             id = idstring[0].strip()
  446.         elif len(idstring) == 3:
  447.             id = idstring[1].strip()
  448.         else:
  449.             return failed
  450.         if len(idstring) == 1 == '':
  451.             return failed
  452.         parts = id.split('.')
  453.         fname = self.defaultFile()
  454.         if len(parts) == 1:
  455.             item = parts[0]
  456.         else:
  457.             f = self.lookupmodule(parts[0])
  458.             if f:
  459.                 fname = f
  460.             
  461.             item = parts[1]
  462.         answer = find_function(item, fname)
  463.         if not answer:
  464.             pass
  465.         return failed
  466.  
  467.     
  468.     def checkline(self, filename, lineno):
  469.         '''Check whether specified line seems to be executable.
  470.  
  471.         Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
  472.         line or EOF). Warning: testing is not comprehensive.
  473.         '''
  474.         line = linecache.getline(filename, lineno, self.curframe.f_globals)
  475.         if not line:
  476.             print >>self.stdout, 'End of file'
  477.             return 0
  478.         line = line.strip()
  479.         if not line and line[0] == '#' and line[:3] == '"""' or line[:3] == "'''":
  480.             print >>self.stdout, '*** Blank or comment'
  481.             return 0
  482.         return lineno
  483.  
  484.     
  485.     def do_enable(self, arg):
  486.         args = arg.split()
  487.         for i in args:
  488.             
  489.             try:
  490.                 i = int(i)
  491.             except ValueError:
  492.                 print >>self.stdout, 'Breakpoint index %r is not a number' % i
  493.                 continue
  494.  
  495.             if i <= i:
  496.                 pass
  497.             elif not i < len(bdb.Breakpoint.bpbynumber):
  498.                 print >>self.stdout, 'No breakpoint numbered', i
  499.                 continue
  500.             
  501.             bp = bdb.Breakpoint.bpbynumber[i]
  502.             if bp:
  503.                 bp.enable()
  504.                 continue
  505.             0
  506.         
  507.  
  508.     
  509.     def do_disable(self, arg):
  510.         args = arg.split()
  511.         for i in args:
  512.             
  513.             try:
  514.                 i = int(i)
  515.             except ValueError:
  516.                 print >>self.stdout, 'Breakpoint index %r is not a number' % i
  517.                 continue
  518.  
  519.             if i <= i:
  520.                 pass
  521.             elif not i < len(bdb.Breakpoint.bpbynumber):
  522.                 print >>self.stdout, 'No breakpoint numbered', i
  523.                 continue
  524.             
  525.             bp = bdb.Breakpoint.bpbynumber[i]
  526.             if bp:
  527.                 bp.disable()
  528.                 continue
  529.             0
  530.         
  531.  
  532.     
  533.     def do_condition(self, arg):
  534.         args = arg.split(' ', 1)
  535.         
  536.         try:
  537.             bpnum = int(args[0].strip())
  538.         except ValueError:
  539.             print >>self.stdout, 'Breakpoint index %r is not a number' % args[0]
  540.             return None
  541.  
  542.         
  543.         try:
  544.             cond = args[1]
  545.         except:
  546.             cond = None
  547.  
  548.         
  549.         try:
  550.             bp = bdb.Breakpoint.bpbynumber[bpnum]
  551.         except IndexError:
  552.             print >>self.stdout, 'Breakpoint index %r is not valid' % args[0]
  553.             return None
  554.  
  555.         if bp:
  556.             bp.cond = cond
  557.             if not cond:
  558.                 print >>self.stdout, 'Breakpoint', bpnum,
  559.                 print >>self.stdout, 'is now unconditional.'
  560.             
  561.         
  562.  
  563.     
  564.     def do_ignore(self, arg):
  565.         '''arg is bp number followed by ignore count.'''
  566.         args = arg.split()
  567.         
  568.         try:
  569.             bpnum = int(args[0].strip())
  570.         except ValueError:
  571.             print >>self.stdout, 'Breakpoint index %r is not a number' % args[0]
  572.             return None
  573.  
  574.         
  575.         try:
  576.             count = int(args[1].strip())
  577.         except:
  578.             count = 0
  579.  
  580.         
  581.         try:
  582.             bp = bdb.Breakpoint.bpbynumber[bpnum]
  583.         except IndexError:
  584.             print >>self.stdout, 'Breakpoint index %r is not valid' % args[0]
  585.             return None
  586.  
  587.         if bp:
  588.             bp.ignore = count
  589.             if count > 0:
  590.                 reply = 'Will ignore next '
  591.                 if count > 1:
  592.                     reply = reply + '%d crossings' % count
  593.                 else:
  594.                     reply = reply + '1 crossing'
  595.                 print >>self.stdout, reply + ' of breakpoint %d.' % bpnum
  596.             else:
  597.                 print >>self.stdout, 'Will stop next time breakpoint',
  598.                 print >>self.stdout, bpnum, 'is reached.'
  599.         
  600.  
  601.     
  602.     def do_clear(self, arg):
  603.         '''Three possibilities, tried in this order:
  604.         clear -> clear all breaks, ask for confirmation
  605.         clear file:lineno -> clear all breaks at file:lineno
  606.         clear bpno bpno ... -> clear breakpoints by number'''
  607.         if not arg:
  608.             
  609.             try:
  610.                 reply = raw_input('Clear all breaks? ')
  611.             except EOFError:
  612.                 reply = 'no'
  613.  
  614.             reply = reply.strip().lower()
  615.             if reply in ('y', 'yes'):
  616.                 self.clear_all_breaks()
  617.             
  618.             return None
  619.         if ':' in arg:
  620.             i = arg.rfind(':')
  621.             filename = arg[:i]
  622.             arg = arg[i + 1:]
  623.             
  624.             try:
  625.                 lineno = int(arg)
  626.             except ValueError:
  627.                 arg
  628.                 arg
  629.                 err = 'Invalid line number (%s)' % arg
  630.             except:
  631.                 arg
  632.  
  633.             err = self.clear_break(filename, lineno)
  634.             return None
  635.         numberlist = arg.split()
  636.         for i in numberlist:
  637.             
  638.             try:
  639.                 i = int(i)
  640.             except ValueError:
  641.                 ':' in arg
  642.                 ':' in arg
  643.                 arg
  644.                 print >>self.stdout, 'Breakpoint index %r is not a number' % i
  645.                 continue
  646.             except:
  647.                 ':' in arg
  648.  
  649.             if i <= i:
  650.                 pass
  651.             elif not i < len(bdb.Breakpoint.bpbynumber):
  652.                 print >>self.stdout, 'No breakpoint numbered', i
  653.                 continue
  654.             
  655.             err = self.clear_bpbynumber(i)
  656.             if err:
  657.                 print >>self.stdout, '***', err
  658.                 continue
  659.             print >>self.stdout, 'Deleted breakpoint', i
  660.         
  661.  
  662.     do_cl = do_clear
  663.     
  664.     def do_where(self, arg):
  665.         self.print_stack_trace()
  666.  
  667.     do_w = do_where
  668.     do_bt = do_where
  669.     
  670.     def do_up(self, arg):
  671.         if self.curindex == 0:
  672.             print >>self.stdout, '*** Oldest frame'
  673.         else:
  674.             self.curindex = self.curindex - 1
  675.             self.curframe = self.stack[self.curindex][0]
  676.             self.print_stack_entry(self.stack[self.curindex])
  677.             self.lineno = None
  678.  
  679.     do_u = do_up
  680.     
  681.     def do_down(self, arg):
  682.         if self.curindex + 1 == len(self.stack):
  683.             print >>self.stdout, '*** Newest frame'
  684.         else:
  685.             self.curindex = self.curindex + 1
  686.             self.curframe = self.stack[self.curindex][0]
  687.             self.print_stack_entry(self.stack[self.curindex])
  688.             self.lineno = None
  689.  
  690.     do_d = do_down
  691.     
  692.     def do_until(self, arg):
  693.         self.set_until(self.curframe)
  694.         return 1
  695.  
  696.     do_unt = do_until
  697.     
  698.     def do_step(self, arg):
  699.         self.set_step()
  700.         return 1
  701.  
  702.     do_s = do_step
  703.     
  704.     def do_next(self, arg):
  705.         self.set_next(self.curframe)
  706.         return 1
  707.  
  708.     do_n = do_next
  709.     
  710.     def do_run(self, arg):
  711.         '''Restart program by raising an exception to be caught in the main debugger
  712.         loop. If arguments were given, set them in sys.argv.'''
  713.         if arg:
  714.             import shlex as shlex
  715.             argv0 = sys.argv[0:1]
  716.             sys.argv = shlex.split(arg)
  717.             sys.argv[:0] = argv0
  718.         
  719.         raise Restart
  720.  
  721.     do_restart = do_run
  722.     
  723.     def do_return(self, arg):
  724.         self.set_return(self.curframe)
  725.         return 1
  726.  
  727.     do_r = do_return
  728.     
  729.     def do_continue(self, arg):
  730.         self.set_continue()
  731.         return 1
  732.  
  733.     do_c = do_cont = do_continue
  734.     
  735.     def do_jump(self, arg):
  736.         if self.curindex + 1 != len(self.stack):
  737.             print >>self.stdout, '*** You can only jump within the bottom frame'
  738.             return None
  739.         
  740.         try:
  741.             arg = int(arg)
  742.         except ValueError:
  743.             self.curindex + 1 != len(self.stack)
  744.             self.curindex + 1 != len(self.stack)
  745.             print >>self.stdout, "*** The 'jump' command requires a line number."
  746.         except:
  747.             self.curindex + 1 != len(self.stack)
  748.  
  749.         
  750.         try:
  751.             self.curframe.f_lineno = arg
  752.             self.stack[self.curindex] = (self.stack[self.curindex][0], arg)
  753.             self.print_stack_entry(self.stack[self.curindex])
  754.         except ValueError:
  755.             self.curindex + 1 != len(self.stack)
  756.             e = self.curindex + 1 != len(self.stack)
  757.             print >>self.stdout, '*** Jump failed:', e
  758.         except:
  759.             self.curindex + 1 != len(self.stack)
  760.  
  761.  
  762.     do_j = do_jump
  763.     
  764.     def do_debug(self, arg):
  765.         sys.settrace(None)
  766.         globals = self.curframe.f_globals
  767.         locals = self.curframe.f_locals
  768.         p = Pdb(self.completekey, self.stdin, self.stdout)
  769.         p.prompt = '(%s) ' % self.prompt.strip()
  770.         print >>self.stdout, 'ENTERING RECURSIVE DEBUGGER'
  771.         sys.call_tracing(p.run, (arg, globals, locals))
  772.         print >>self.stdout, 'LEAVING RECURSIVE DEBUGGER'
  773.         sys.settrace(self.trace_dispatch)
  774.         self.lastcmd = p.lastcmd
  775.  
  776.     
  777.     def do_quit(self, arg):
  778.         self._user_requested_quit = 1
  779.         self.set_quit()
  780.         return 1
  781.  
  782.     do_q = do_quit
  783.     do_exit = do_quit
  784.     
  785.     def do_EOF(self, arg):
  786.         print >>self.stdout
  787.         self._user_requested_quit = 1
  788.         self.set_quit()
  789.         return 1
  790.  
  791.     
  792.     def do_args(self, arg):
  793.         f = self.curframe
  794.         co = f.f_code
  795.         dict = f.f_locals
  796.         n = co.co_argcount
  797.         if co.co_flags & 4:
  798.             n = n + 1
  799.         
  800.         if co.co_flags & 8:
  801.             n = n + 1
  802.         
  803.         for i in range(n):
  804.             name = co.co_varnames[i]
  805.             print >>self.stdout, name, '=',
  806.             if name in dict:
  807.                 print >>self.stdout, dict[name]
  808.                 continue
  809.             print >>self.stdout, '*** undefined ***'
  810.         
  811.  
  812.     do_a = do_args
  813.     
  814.     def do_retval(self, arg):
  815.         if '__return__' in self.curframe.f_locals:
  816.             print >>self.stdout, self.curframe.f_locals['__return__']
  817.         else:
  818.             print >>self.stdout, '*** Not yet returned!'
  819.  
  820.     do_rv = do_retval
  821.     
  822.     def _getval(self, arg):
  823.         
  824.         try:
  825.             return eval(arg, self.curframe.f_globals, self.curframe.f_locals)
  826.         except:
  827.             (t, v) = sys.exc_info()[:2]
  828.             if isinstance(t, str):
  829.                 exc_type_name = t
  830.             else:
  831.                 exc_type_name = t.__name__
  832.             print >>self.stdout, '***', exc_type_name + ':', repr(v)
  833.             raise 
  834.  
  835.  
  836.     
  837.     def do_p(self, arg):
  838.         
  839.         try:
  840.             print >>self.stdout, repr(self._getval(arg))
  841.         except:
  842.             pass
  843.  
  844.  
  845.     
  846.     def do_pp(self, arg):
  847.         
  848.         try:
  849.             pprint.pprint(self._getval(arg), self.stdout)
  850.         except:
  851.             pass
  852.  
  853.  
  854.     
  855.     def do_list(self, arg):
  856.         self.lastcmd = 'list'
  857.         last = None
  858.         if arg:
  859.             
  860.             try:
  861.                 x = eval(arg, { }, { })
  862.                 if type(x) == type(()):
  863.                     (first, last) = x
  864.                     first = int(first)
  865.                     last = int(last)
  866.                     if last < first:
  867.                         last = first + last
  868.                     
  869.                 else:
  870.                     first = max(1, int(x) - 5)
  871.             print >>self.stdout, '*** Error in argument:', repr(arg)
  872.             return None
  873.  
  874.         elif self.lineno is None:
  875.             first = max(1, self.curframe.f_lineno - 5)
  876.         else:
  877.             first = self.lineno + 1
  878.         if last is None:
  879.             last = first + 10
  880.         
  881.         filename = self.curframe.f_code.co_filename
  882.         breaklist = self.get_file_breaks(filename)
  883.         
  884.         try:
  885.             for lineno in range(first, last + 1):
  886.                 line = linecache.getline(filename, lineno, self.curframe.f_globals)
  887.                 if not line:
  888.                     print >>self.stdout, '[EOF]'
  889.                     break
  890.                     continue
  891.                 s = repr(lineno).rjust(3)
  892.                 if len(s) < 4:
  893.                     s = s + ' '
  894.                 
  895.                 if lineno in breaklist:
  896.                     s = s + 'B'
  897.                 else:
  898.                     s = s + ' '
  899.                 if lineno == self.curframe.f_lineno:
  900.                     s = s + '->'
  901.                 
  902.                 print >>self.stdout, s + '\t' + line,
  903.                 self.lineno = lineno
  904.         except KeyboardInterrupt:
  905.             pass
  906.  
  907.  
  908.     do_l = do_list
  909.     
  910.     def do_whatis(self, arg):
  911.         
  912.         try:
  913.             value = eval(arg, self.curframe.f_globals, self.curframe.f_locals)
  914.         except:
  915.             (t, v) = sys.exc_info()[:2]
  916.             if type(t) == type(''):
  917.                 exc_type_name = t
  918.             else:
  919.                 exc_type_name = t.__name__
  920.             print >>self.stdout, '***', exc_type_name + ':', repr(v)
  921.             return None
  922.  
  923.         code = None
  924.         
  925.         try:
  926.             code = value.func_code
  927.         except:
  928.             pass
  929.  
  930.         if code:
  931.             print >>self.stdout, 'Function', code.co_name
  932.             return None
  933.         
  934.         try:
  935.             code = value.im_func.func_code
  936.         except:
  937.             code
  938.  
  939.         if code:
  940.             print >>self.stdout, 'Method', code.co_name
  941.             return None
  942.         print >>self.stdout, type(value)
  943.  
  944.     
  945.     def do_alias(self, arg):
  946.         args = arg.split()
  947.         if len(args) == 0:
  948.             keys = self.aliases.keys()
  949.             keys.sort()
  950.             for alias in keys:
  951.                 print >>self.stdout, '%s = %s' % (alias, self.aliases[alias])
  952.             
  953.             return None
  954.  
  955.     
  956.     def do_unalias(self, arg):
  957.         args = arg.split()
  958.         if len(args) == 0:
  959.             return None
  960.         if args[0] in self.aliases:
  961.             del self.aliases[args[0]]
  962.         
  963.  
  964.     commands_resuming = [
  965.         'do_continue',
  966.         'do_step',
  967.         'do_next',
  968.         'do_return',
  969.         'do_quit',
  970.         'do_jump']
  971.     
  972.     def print_stack_trace(self):
  973.         
  974.         try:
  975.             for frame_lineno in self.stack:
  976.                 self.print_stack_entry(frame_lineno)
  977.         except KeyboardInterrupt:
  978.             pass
  979.  
  980.  
  981.     
  982.     def print_stack_entry(self, frame_lineno, prompt_prefix = line_prefix):
  983.         (frame, lineno) = frame_lineno
  984.         if frame is self.curframe:
  985.             print >>self.stdout, '>',
  986.         else:
  987.             print >>self.stdout, ' ',
  988.         print >>self.stdout, self.format_stack_entry(frame_lineno, prompt_prefix)
  989.  
  990.     
  991.     def help_help(self):
  992.         self.help_h()
  993.  
  994.     
  995.     def help_h(self):
  996.         print >>self.stdout, 'h(elp)\nWithout argument, print the list of available commands.\nWith a command name as argument, print help about that command\n"help pdb" pipes the full documentation file to the $PAGER\n"help exec" gives help on the ! command'
  997.  
  998.     
  999.     def help_where(self):
  1000.         self.help_w()
  1001.  
  1002.     
  1003.     def help_w(self):
  1004.         print >>self.stdout, 'w(here)\nPrint a stack trace, with the most recent frame at the bottom.\nAn arrow indicates the "current frame", which determines the\ncontext of most commands.  \'bt\' is an alias for this command.'
  1005.  
  1006.     help_bt = help_w
  1007.     
  1008.     def help_down(self):
  1009.         self.help_d()
  1010.  
  1011.     
  1012.     def help_d(self):
  1013.         print >>self.stdout, 'd(own)\nMove the current frame one level down in the stack trace\n(to a newer frame).'
  1014.  
  1015.     
  1016.     def help_up(self):
  1017.         self.help_u()
  1018.  
  1019.     
  1020.     def help_u(self):
  1021.         print >>self.stdout, 'u(p)\nMove the current frame one level up in the stack trace\n(to an older frame).'
  1022.  
  1023.     
  1024.     def help_break(self):
  1025.         self.help_b()
  1026.  
  1027.     
  1028.     def help_b(self):
  1029.         print >>self.stdout, "b(reak) ([file:]lineno | function) [, condition]\nWith a line number argument, set a break there in the current\nfile.  With a function name, set a break at first executable line\nof that function.  Without argument, list all breaks.  If a second\nargument is present, it is a string specifying an expression\nwhich must evaluate to true before the breakpoint is honored.\n\nThe line number may be prefixed with a filename and a colon,\nto specify a breakpoint in another file (probably one that\nhasn't been loaded yet).  The file is searched for on sys.path;\nthe .py suffix may be omitted."
  1030.  
  1031.     
  1032.     def help_clear(self):
  1033.         self.help_cl()
  1034.  
  1035.     
  1036.     def help_cl(self):
  1037.         print >>self.stdout, 'cl(ear) filename:lineno'
  1038.         print >>self.stdout, 'cl(ear) [bpnumber [bpnumber...]]\nWith a space separated list of breakpoint numbers, clear\nthose breakpoints.  Without argument, clear all breaks (but\nfirst ask confirmation).  With a filename:lineno argument,\nclear all breaks at that line in that file.\n\nNote that the argument is different from previous versions of\nthe debugger (in python distributions 1.5.1 and before) where\na linenumber was used instead of either filename:lineno or\nbreakpoint numbers.'
  1039.  
  1040.     
  1041.     def help_tbreak(self):
  1042.         print >>self.stdout, 'tbreak  same arguments as break, but breakpoint is\nremoved when first hit.'
  1043.  
  1044.     
  1045.     def help_enable(self):
  1046.         print >>self.stdout, 'enable bpnumber [bpnumber ...]\nEnables the breakpoints given as a space separated list of\nbp numbers.'
  1047.  
  1048.     
  1049.     def help_disable(self):
  1050.         print >>self.stdout, 'disable bpnumber [bpnumber ...]\nDisables the breakpoints given as a space separated list of\nbp numbers.'
  1051.  
  1052.     
  1053.     def help_ignore(self):
  1054.         print >>self.stdout, 'ignore bpnumber count\nSets the ignore count for the given breakpoint number.  A breakpoint\nbecomes active when the ignore count is zero.  When non-zero, the\ncount is decremented each time the breakpoint is reached and the\nbreakpoint is not disabled and any associated condition evaluates\nto true.'
  1055.  
  1056.     
  1057.     def help_condition(self):
  1058.         print >>self.stdout, 'condition bpnumber str_condition\nstr_condition is a string specifying an expression which\nmust evaluate to true before the breakpoint is honored.\nIf str_condition is absent, any existing condition is removed;\ni.e., the breakpoint is made unconditional.'
  1059.  
  1060.     
  1061.     def help_step(self):
  1062.         self.help_s()
  1063.  
  1064.     
  1065.     def help_s(self):
  1066.         print >>self.stdout, 's(tep)\nExecute the current line, stop at the first possible occasion\n(either in a function that is called or in the current function).'
  1067.  
  1068.     
  1069.     def help_until(self):
  1070.         self.help_unt()
  1071.  
  1072.     
  1073.     def help_unt(self):
  1074.         print 'unt(il)\nContinue execution until the line with a number greater than the current\none is reached or until the current frame returns'
  1075.  
  1076.     
  1077.     def help_next(self):
  1078.         self.help_n()
  1079.  
  1080.     
  1081.     def help_n(self):
  1082.         print >>self.stdout, 'n(ext)\nContinue execution until the next line in the current function\nis reached or it returns.'
  1083.  
  1084.     
  1085.     def help_return(self):
  1086.         self.help_r()
  1087.  
  1088.     
  1089.     def help_r(self):
  1090.         print >>self.stdout, 'r(eturn)\nContinue execution until the current function returns.'
  1091.  
  1092.     
  1093.     def help_continue(self):
  1094.         self.help_c()
  1095.  
  1096.     
  1097.     def help_cont(self):
  1098.         self.help_c()
  1099.  
  1100.     
  1101.     def help_c(self):
  1102.         print >>self.stdout, 'c(ont(inue))\nContinue execution, only stop when a breakpoint is encountered.'
  1103.  
  1104.     
  1105.     def help_jump(self):
  1106.         self.help_j()
  1107.  
  1108.     
  1109.     def help_j(self):
  1110.         print >>self.stdout, 'j(ump) lineno\nSet the next line that will be executed.'
  1111.  
  1112.     
  1113.     def help_debug(self):
  1114.         print >>self.stdout, 'debug code\nEnter a recursive debugger that steps through the code argument\n(which is an arbitrary expression or statement to be executed\nin the current environment).'
  1115.  
  1116.     
  1117.     def help_list(self):
  1118.         self.help_l()
  1119.  
  1120.     
  1121.     def help_l(self):
  1122.         print >>self.stdout, 'l(ist) [first [,last]]\nList source code for the current file.\nWithout arguments, list 11 lines around the current line\nor continue the previous listing.\nWith one argument, list 11 lines starting at that line.\nWith two arguments, list the given range;\nif the second argument is less than the first, it is a count.'
  1123.  
  1124.     
  1125.     def help_args(self):
  1126.         self.help_a()
  1127.  
  1128.     
  1129.     def help_a(self):
  1130.         print >>self.stdout, 'a(rgs)\nPrint the arguments of the current function.'
  1131.  
  1132.     
  1133.     def help_p(self):
  1134.         print >>self.stdout, 'p expression\nPrint the value of the expression.'
  1135.  
  1136.     
  1137.     def help_pp(self):
  1138.         print >>self.stdout, 'pp expression\nPretty-print the value of the expression.'
  1139.  
  1140.     
  1141.     def help_exec(self):
  1142.         print >>self.stdout, "(!) statement\nExecute the (one-line) statement in the context of\nthe current stack frame.\nThe exclamation point can be omitted unless the first word\nof the statement resembles a debugger command.\nTo assign to a global variable you must always prefix the\ncommand with a 'global' command, e.g.:\n(Pdb) global list_options; list_options = ['-l']\n(Pdb)"
  1143.  
  1144.     
  1145.     def help_run(self):
  1146.         print 'run [args...]\nRestart the debugged python program. If a string is supplied, it is\nsplitted with "shlex" and the result is used as the new sys.argv.\nHistory, breakpoints, actions and debugger options are preserved.\n"restart" is an alias for "run".'
  1147.  
  1148.     help_restart = help_run
  1149.     
  1150.     def help_quit(self):
  1151.         self.help_q()
  1152.  
  1153.     
  1154.     def help_q(self):
  1155.         print >>self.stdout, 'q(uit) or exit - Quit from the debugger.\nThe program being executed is aborted.'
  1156.  
  1157.     help_exit = help_q
  1158.     
  1159.     def help_whatis(self):
  1160.         print >>self.stdout, 'whatis arg\nPrints the type of the argument.'
  1161.  
  1162.     
  1163.     def help_EOF(self):
  1164.         print >>self.stdout, 'EOF\nHandles the receipt of EOF as a command.'
  1165.  
  1166.     
  1167.     def help_alias(self):
  1168.         print >>self.stdout, 'alias [name [command [parameter parameter ...] ]]\nCreates an alias called \'name\' the executes \'command\'.  The command\nmust *not* be enclosed in quotes.  Replaceable parameters are\nindicated by %1, %2, and so on, while %* is replaced by all the\nparameters.  If no command is given, the current alias for name\nis shown. If no name is given, all aliases are listed.\n\nAliases may be nested and can contain anything that can be\nlegally typed at the pdb prompt.  Note!  You *can* override\ninternal pdb commands with aliases!  Those internal commands\nare then hidden until the alias is removed.  Aliasing is recursively\napplied to the first word of the command line; all other words\nin the line are left alone.\n\nSome useful aliases (especially when placed in the .pdbrc file) are:\n\n#Print instance variables (usage "pi classInst")\nalias pi for k in %1.__dict__.keys(): print "%1.",k,"=",%1.__dict__[k]\n\n#Print instance variables in self\nalias ps pi self\n'
  1169.  
  1170.     
  1171.     def help_unalias(self):
  1172.         print >>self.stdout, 'unalias name\nDeletes the specified alias.'
  1173.  
  1174.     
  1175.     def help_commands(self):
  1176.         print >>self.stdout, "commands [bpnumber]\n(com) ...\n(com) end\n(Pdb)\n\nSpecify a list of commands for breakpoint number bpnumber.  The\ncommands themselves appear on the following lines.  Type a line\ncontaining just 'end' to terminate the commands.\n\nTo remove all commands from a breakpoint, type commands and\nfollow it immediately with  end; that is, give no commands.\n\nWith no bpnumber argument, commands refers to the last\nbreakpoint set.\n\nYou can use breakpoint commands to start your program up again.\nSimply use the continue command, or step, or any other\ncommand that resumes execution.\n\nSpecifying any command resuming execution (currently continue,\nstep, next, return, jump, quit and their abbreviations) terminates\nthe command list (as if that command was immediately followed by end).\nThis is because any time you resume execution\n(even with a simple next or step), you may encounter\nanother breakpoint--which could have its own command list, leading to\nambiguities about which list to execute.\n\n   If you use the 'silent' command in the command list, the\nusual message about stopping at a breakpoint is not printed.  This may\nbe desirable for breakpoints that are to print a specific message and\nthen continue.  If none of the other commands print anything, you\nsee no sign that the breakpoint was reached.\n"
  1177.  
  1178.     
  1179.     def help_pdb(self):
  1180.         help()
  1181.  
  1182.     
  1183.     def lookupmodule(self, filename):
  1184.         '''Helper function for break/clear parsing -- may be overridden.
  1185.  
  1186.         lookupmodule() translates (possibly incomplete) file or module name
  1187.         into an absolute file name.
  1188.         '''
  1189.         if os.path.isabs(filename) and os.path.exists(filename):
  1190.             return filename
  1191.         f = os.path.join(sys.path[0], filename)
  1192.         if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
  1193.             return f
  1194.         (root, ext) = os.path.splitext(filename)
  1195.         if os.path.isabs(filename):
  1196.             return filename
  1197.         for dirname in sys.path:
  1198.             while os.path.islink(dirname):
  1199.                 dirname = os.readlink(dirname)
  1200.                 continue
  1201.                 os.path.isabs(filename)
  1202.             fullname = os.path.join(dirname, filename)
  1203.             if os.path.exists(fullname):
  1204.                 return fullname
  1205.         
  1206.  
  1207.     
  1208.     def _runscript(self, filename):
  1209.         import __main__
  1210.         __main__.__dict__.clear()
  1211.         __main__.__dict__.update({
  1212.             '__name__': '__main__',
  1213.             '__file__': filename,
  1214.             '__builtins__': __builtins__ })
  1215.         self._wait_for_mainpyfile = 1
  1216.         self.mainpyfile = self.canonic(filename)
  1217.         self._user_requested_quit = 0
  1218.         statement = 'execfile( "%s")' % filename
  1219.         self.run(statement)
  1220.  
  1221.  
  1222.  
  1223. def run(statement, globals = None, locals = None):
  1224.     Pdb().run(statement, globals, locals)
  1225.  
  1226.  
  1227. def runeval(expression, globals = None, locals = None):
  1228.     return Pdb().runeval(expression, globals, locals)
  1229.  
  1230.  
  1231. def runctx(statement, globals, locals):
  1232.     run(statement, globals, locals)
  1233.  
  1234.  
  1235. def runcall(*args, **kwds):
  1236.     return Pdb().runcall(*args, **kwds)
  1237.  
  1238.  
  1239. def set_trace():
  1240.     Pdb().set_trace(sys._getframe().f_back)
  1241.  
  1242.  
  1243. def post_mortem(t = None):
  1244.     if t is None:
  1245.         t = sys.exc_info()[2]
  1246.         if t is None:
  1247.             raise ValueError('A valid traceback must be passed if no exception is being handled')
  1248.         t is None
  1249.     
  1250.     p = Pdb()
  1251.     p.reset()
  1252.     p.interaction(None, t)
  1253.  
  1254.  
  1255. def pm():
  1256.     post_mortem(sys.last_traceback)
  1257.  
  1258. TESTCMD = 'import x; x.main()'
  1259.  
  1260. def test():
  1261.     run(TESTCMD)
  1262.  
  1263.  
  1264. def help():
  1265.     for dirname in sys.path:
  1266.         fullname = os.path.join(dirname, 'pdb.doc')
  1267.         if os.path.exists(fullname):
  1268.             sts = os.system('${PAGER-more} ' + fullname)
  1269.             if sts:
  1270.                 print '*** Pager exit status:', sts
  1271.             
  1272.             break
  1273.             continue
  1274.     else:
  1275.         print 'Sorry, can\'t find the help file "pdb.doc"', 'along the Python search path'
  1276.  
  1277.  
  1278. def main():
  1279.     if not sys.argv[1:] or sys.argv[1] in ('--help', '-h'):
  1280.         print 'usage: pdb.py scriptfile [arg] ...'
  1281.         sys.exit(2)
  1282.     
  1283.     mainpyfile = sys.argv[1]
  1284.     if not os.path.exists(mainpyfile):
  1285.         print 'Error:', mainpyfile, 'does not exist'
  1286.         sys.exit(1)
  1287.     
  1288.     del sys.argv[0]
  1289.     sys.path[0] = os.path.dirname(mainpyfile)
  1290.     pdb = Pdb()
  1291.     while None:
  1292.         
  1293.         try:
  1294.             pdb._runscript(mainpyfile)
  1295.             if pdb._user_requested_quit:
  1296.                 break
  1297.             
  1298.             print 'The program finished and will be restarted'
  1299.         continue
  1300.         except Restart:
  1301.             print 'Restarting', mainpyfile, 'with arguments:'
  1302.             print '\t' + ' '.join(sys.argv[1:])
  1303.             continue
  1304.             except SystemExit:
  1305.                 print 'The program exited via sys.exit(). Exit status: ', sys.exc_info()[1]
  1306.                 continue
  1307.                 traceback.print_exc()
  1308.                 print 'Uncaught exception. Entering post mortem debugging'
  1309.                 print "Running 'cont' or 'step' will restart the program"
  1310.                 t = sys.exc_info()[2]
  1311.                 pdb.interaction(None, t)
  1312.                 print 'Post mortem debugger finished. The ' + mainpyfile + ' will be restarted'
  1313.                 continue
  1314.             
  1315.             return None
  1316.  
  1317.  
  1318. if __name__ == '__main__':
  1319.     import pdb
  1320.     pdb.main()
  1321.  
  1322.